/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.common.util.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.net.URL;
import java.nio.file.Files;

/**
 *
 * @author tnmkhoi
 */
public class IoUtils {

  public static File loadFileFromClassPath(String path) {
    URL fileUrl = IoUtils.class.getClassLoader().getResource(path);
    String relativePath = fileUrl.getFile();
    File f = new File(relativePath);
    return f;
  }

  public static String getRelativePathFromClassPath(String path) {
    URL fileUrl = IoUtils.class.getClassLoader().getResource(path);
    String relativePath = fileUrl.getFile();
    return relativePath;
  }

  /**
   * @param o if null, ???
   * @param file
   * @throws java.lang.Exception
   */
  public static void saveObject(Serializable o, File file) throws IOException {
    if (!file.exists()) {
      FileMovingUtils.createFileTree(file);
    }
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
    out.writeObject(o);
    out.close();
  }

  public static void saveString(String s, File file) throws IOException {
    if (!file.exists()) {
      FileMovingUtils.createFileTree(file);
    }
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
//    PrintWriter out = new PrintWriter(file);
    out.write(s);
    out.close();
  }

  public static Object loadObject(File file) throws IOException, ClassNotFoundException {
    Object rs = null;
    if (!file.exists()) {
      return null;
    }
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    rs = in.readObject();
    in.close();
    return rs;
  }

  public static String loadString(File file) throws IOException {
    Object rs = null;
    if (!file.exists()) {
      return null;
    }
    byte[] encoded = Files.readAllBytes(file.toPath());
    return new String(encoded);
//          
//    PrintReader in = new PrintReader(new FileInputStream(file));
//    rs = in.readObject();
//    in.close();
//    return rs;
  }
}
